package cn.csc.module.distribute.service.distributor;

import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.security.core.util.SecurityFrameworkUtils;
import cn.csc.module.distribute.api.distributor.dto.DistributorReqDTO;
import cn.csc.module.distribute.controller.admin.distributor.vo.DistributorExportReqVO;
import cn.csc.module.distribute.controller.admin.distributor.vo.DistributorPageReqVO;
import cn.csc.module.distribute.controller.admin.distributor.vo.DistributorUpdateReqVO;
import cn.csc.module.distribute.controller.app.distributor.vo.AppDistributeInfoRespVO;
import cn.csc.module.distribute.controller.app.distributor.vo.AppDistributorCreateReqVO;
import cn.csc.module.distribute.controller.app.distributor.vo.AppDistributorReqVO;
import cn.csc.module.distribute.convert.distributor.DistributorConvert;
import cn.csc.module.distribute.dal.dataobject.audit.DistributorAuditDO;
import cn.csc.module.distribute.dal.dataobject.distributor.DistributorDO;
import cn.csc.module.distribute.dal.mysql.audit.DistributorAuditMapper;
import cn.csc.module.distribute.dal.mysql.distributor.DistributorMapper;
import cn.csc.module.member.api.user.MemberUserApi;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.csc.module.distribute.enums.ErrorCodeConstants.DISTRIBUTOR_NOT_EXISTS;

/**
 * 分销员信息 Service 实现类
 *
 * @author liuchuang
 */
@Slf4j
@Service
@Validated
public class DistributorServiceImpl extends ServiceImpl<DistributorMapper, DistributorDO> implements DistributorService {

    @Resource
    private DistributorAuditMapper distributorAuditMapper;
    @Resource
    MemberUserApi memberUserApi;


    @Override
    public BigInteger createDistributor(AppDistributorCreateReqVO createReqVO) {
        log.info("createDistributor req: {}",createReqVO);
        // 插入
        Long userId = getLoginUserId();
        DistributorDO distributor = DistributorConvert.INSTANCE.convert(createReqVO);
        distributor.setInviteCode(IdUtil.fastSimpleUUID().substring(0,32));
        distributor.setUserId(BigInteger.valueOf(userId));
        // 首次申请和重新申请都设置为待审核
        distributor.setStatus((byte)0);

        DistributorAuditDO distributorAuditDO = new DistributorAuditDO();
        DistributorDO distributorDO = baseMapper.selectByUserId(BigInteger.valueOf(userId));
        if (distributorDO != null){
            // 构建条件构造器（以唯一键 "userId" 为例）
            UpdateWrapper<DistributorDO> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("user_id", userId);
            update(distributor,updateWrapper);
            log.info("createDistributor : {}",distributor);
            distributorAuditDO.setDistributorId(distributorDO.getId());
        } else {
            save(distributor);
            distributorAuditDO.setDistributorId(distributor.getId());
        }
        log.info("createDistributor distributor: {}",distributor);

        distributorAuditDO.setUserId(BigInteger.valueOf(userId));
        distributorAuditDO.setDistributorName(createReqVO.getName());
        distributorAuditDO.setAuditStatus((byte)0);
        distributorAuditDO.setCreator(String.valueOf(userId));
        distributorAuditDO.setUpdater(String.valueOf(userId));

        distributorAuditMapper.insert(distributorAuditDO);

        // 返回
        return distributorDO == null ? distributor.getId() : distributorDO.getId();
    }

    @Override
    public void updateDistributor(DistributorUpdateReqVO updateReqVO) {
        // 校验存在
        validateDistributorExists(updateReqVO.getId());
        // 更新
        DistributorDO updateObj = DistributorConvert.INSTANCE.convert(updateReqVO);
        baseMapper.updateById(updateObj);
    }

    @Override
    public void deleteDistributor(BigInteger id) {
        // 校验存在
        validateDistributorExists(id);
        // 删除
        baseMapper.deleteById(id);
    }

    private void validateDistributorExists(BigInteger id) {
        if (baseMapper.selectById(id) == null) {
            throw exception(DISTRIBUTOR_NOT_EXISTS);
        }
    }

    @Override
    public DistributorDO getDistributor(BigInteger id) {
        return baseMapper.selectById(id);
    }

    @Override
    public DistributorDO getByChildUserId(BigInteger childUserId){
        return baseMapper.selectByChildId(childUserId);
    }

    @Override
    public AppDistributeInfoRespVO getDistributeInfo(BigInteger userId){
        DistributorDO distributorDO = baseMapper.selectByUserId(userId);
        AppDistributeInfoRespVO respVO = DistributorConvert.INSTANCE.convert3(distributorDO);
        if (distributorDO != null){
            long count = distributorAuditMapper.selectCountByUserId(userId, false);
            respVO.setHasReadCount(count);
            DistributorAuditDO distributorAuditDO = distributorAuditMapper.selectCommentByUserId(userId);
            if (distributorAuditDO != null){
                respVO.setAuditComment(distributorAuditDO.getAuditComment());
            }
        }
        return respVO;
    }

    @Override
    public String getDistributeWxCode(BigInteger userId){
        DistributorDO distributorDO = baseMapper.selectByUserId(userId);
        return distributorDO != null ? distributorDO.getDistributeWxCode() : "";
    }


    @Override
    public PageResult<DistributorDO> getDistributorPage(DistributorPageReqVO pageReqVO) {
        return baseMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DistributorDO> getDistributorList(DistributorExportReqVO exportReqVO) {
        return baseMapper.selectList(exportReqVO);
    }

    @Override
    public DistributorDO getDistributorById(AppDistributorReqVO reqVO) {
        //reqVO.setUserId(new BigInteger(String.valueOf("1861315910281293825")));
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        reqVO.setUserId(new BigInteger(String.valueOf(userId)));
        reqVO.setStatus(1);
        return baseMapper.getDistributorByUserId(reqVO);
    }

    @Override
    public void pening(DistributorReqDTO reqDTO) {
          baseMapper.updateDistributorPending(reqDTO.getUserId(),reqDTO.getAmount());
    }

    @Override
    public void withdrawable(DistributorReqDTO reqDTO) {
          baseMapper.updateTotalAndWithdrawable(reqDTO.getUserId(),reqDTO.getAmount(),reqDTO.getOrderNum());
    }
}
